#include "httpserve.hpp"
#include "Util.hpp"
#include <sys/stat.h>
#include <sstream>

void func(request &req, response &rep)
{
    req.parse();
    std::cout << "#################################" << std::endl;
    std::cout << req._packet << std::endl;
    std::cout << "Get : " << req.Get << std::endl;
    std::cout << "url : " << req.url << std::endl;
    std::cout << "httpversion :" << req.httpversion << std::endl;
    std::cout << "path :" << req.path << std::endl;
    std::cout << "#################################" << std::endl;
    std::string onbuffer;
    onbuffer.resize(4096);
    util::ReadFile(req.path, (char *)onbuffer.c_str());

    std::string respline = "HTTP/1.1 200 OK\r\n";
    std::string respheader = "Content-Type: text/html\r\n";

    std::string resphead = "Content-Length:";
    struct stat st;
    int n = stat(req.path.c_str(), &st);
    if(n == 0) resphead += std::to_string(st.st_size);
    else resphead += std::to_string(-1);
    resphead += "\r\n";
    
    std::string respblank = "\r\n";

    rep.outbuffer += respline;
    rep.outbuffer += respheader;
    rep.outbuffer += resphead;
    rep.outbuffer += respblank;
    rep.outbuffer += onbuffer;

    std::cout << rep.outbuffer << std::endl;
    std::cout << "#################################" << std::endl;
    return;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage:\n\t" << argv[0] << " local_port" << std::endl;
        exit(-1);
    }
    uint16_t port = atoi(argv[1]);
    httpserve serve(func, port);
    serve.init();
    serve.start();

    return 0;
}